package com.pan.download5.driver;

import com.pan.crawler.Page;
import com.pan.download5.config.TaskHandleConfig;
import com.pan.download5.ctrl.ChapterSyncWriter;
import com.pan.download5.ctrl.TaskSyncPublish;
import com.pan.download5.factory.PageFactory;
import com.pan.entity.Chapter;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TaskHandleImpl2 implements TaskHandle, TaskHandleConfig {

 ;
    private TaskSyncPublish taskPublish;
    private ChapterSyncWriter chapterSyncWriter;
    private CountDownLatch countDownLatch;

    private Page page = null;


    public TaskHandleImpl2(Page page, TaskSyncPublish taskPublish,
                                  ChapterSyncWriter chapterSyncWriter, CountDownLatch countDownLatch) {
        this.page = page;
        this.taskPublish = taskPublish;
        this.chapterSyncWriter = chapterSyncWriter;
        this.countDownLatch = countDownLatch;
    }

    public TaskHandleImpl2(PageFactory pageFactory, TaskSyncPublish taskPublish,
                          ChapterSyncWriter chapterSyncWriter, CountDownLatch countDownLatch) {
        this.page = pageFactory.createPage();
        this.taskPublish = taskPublish;
        this.chapterSyncWriter = chapterSyncWriter;
        this.countDownLatch = countDownLatch;
    }


    private final int errorCount = this.getErrorCount();
    private final int errorWait = this.getErrorWait();//Unit: Milli Seconds
    private final  boolean isClearTitle = this.getClearTitle();

    //这是多次匹配章节名序号的正则，有点章节名有两个序号
    private final  String clearChapterIdRegex = "^(\\s*第?\\s*(?:[一二两三四五六七八九十百千万0〇零]+|\\d+)\\s*[\\.、]?\\s*[章节回]?、?)+";
    //这是单次匹配
    //    private final String clearChapterIdRegex = "^\\s*第?\\s*(?:[一二两三四五六七八九十百千万0〇零]+|\\d+)\\s*[\\.、]?\\s*[章节回]?、?";
//    private final String clearChapterIdRegex = "(^\\d+)|(第\\s*[一壹二两贰三卅四肆五六七八九十百千万〇零\\d]+\\s*[章节回])";

    private final String clearRepeatTitleRegex = "(.+)[\\s,\\./\\\\，。、]*?\\1$";

    /**
     * @param title
     * @param  chapterId 这个id是 从0开始的
     * @return
     */
    private String clearTitle(String title, int chapterId) {
        if (isClearTitle) {
            Matcher repeatMatcher = Pattern.compile(clearRepeatTitleRegex).matcher(title);
            StringBuffer sb = new StringBuffer();
            if (repeatMatcher.find()) {
                String group = repeatMatcher.group(1);
                repeatMatcher.appendReplacement(sb, group);//loop end
                repeatMatcher.appendTail(sb);
                title = sb.toString();
            }
            title = title.replaceFirst(clearChapterIdRegex, "");
        }
        String clearTitle = "第" + (chapterId+1) + "章 " + title.trim();
        return clearTitle;
    }

    @Override
    public void run() {
        while (true) {
            Chapter task = taskPublish.publish();
            if (task == null){
                try {Thread.sleep(errorWait);} catch (InterruptedException e) {throw new RuntimeException(e);}
                task = taskPublish.publish();
                if (task == null) break;
            }
            int id = task.getId();
            String title = task.getTitle();
            title = clearTitle(title,id);//标准化章节序号
            String content = null;
            for (int i = 0; i < errorCount; i++) {
                try {
                    content  = page.get(task);
                    break;
                }catch (Exception e){
                    String errorMessage = i+" id: " + id + " title: " + title + "  爬取失败";
                    System.out.println(errorMessage);
                    System.out.println(e);
                    if (i == errorCount-1) {
                        System.out.println(errorMessage+"次爬取失败，放弃爬取");
                        content = errorMessage;
                        break;
                    }
                }
                try {Thread.sleep(errorWait);} catch (InterruptedException e) {throw new RuntimeException(e);}
                System.out.println("正在开始重新爬取！");
            }
            String writeContent = String.format("%s\n\n\n\n%s\n\n\n\n\n", title, content );
            chapterSyncWriter.writeChapter(id,writeContent);
            System.out.println("爬取章节完成：" + title);
        }
        page.close();
        countDownLatch.countDown();
    }
}
